package Screens;



import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VolumeControl;

import resource.GameScreen;
import resource.Keyboard;
import resource.MenuScreen;
import resource.SaveGame;
import resource.Sound;

import Game.CanvasGame;
import Objects.Dice;
import Objects.Statistic;

public class Game extends Screen {
	private static final int WIN = 1;
	private static final int LOSE = -1;
	private static final int CONTINUE = 0;
	
	private Image[] img;
	private Dice diceOne;
	private Dice diceTwo;
	private Dice diceThree;
	private Statistic statistic;
	private Sprite sprite;
	private int bet; 	//so tien dat cuoc
	private SaveGame saveGame;
	private long startTime;
    private long currTime;
    private VolumeControl vc;
	public Game(CanvasGame _canvas) {
		super(_canvas);
		statistic = new Statistic();
		initMenu();
	}
	
	
	public Statistic getStatistic() {
		return statistic;
	}

	public void setStatistic(Statistic statistic) {
		this.statistic = statistic;
	}
	
	public boolean initMenu(){
		//res = new GameScreen();
		img = new Image[GameScreen.IMG_LENGHT];
		diceOne = new Dice();
		diceTwo = new Dice();
		diceThree = new Dice();
		bet = statistic.getBet();
		saveGame = new SaveGame();
		startTime = System.currentTimeMillis();
		currTime = 0;
		//saveGame = null;
		load_screen();
		return true;
	}
	
	
	
	public void load_screen() {
		// TODO Auto-generated method stub
		for (int i = 0; i < GameScreen.IMG_LENGHT; i++) {
			load(i);
		}
		sprite = new Sprite(img[GameScreen.DICE], 25, 25);
	}
	
	public void un_load_screen() {
		// TODO Auto-generated method stub
		//img = null;
		if(img == null)    return;
        for (int i = 0; i < GameScreen.IMG_LENGHT; i++) {
            unLoad(i);
        }
	}


	public boolean load(int i) {
		/* TODO: load the images here */
	    try {
	    	img[i] = Image.createImage(GameScreen.imgSource[i]);
	    } catch (Exception ex) {
	    	System.err.println(ex.toString());
	    	return false;
	    }
	    return true;
	}
	
	public void unLoad(int i) {
        /* TODO: make sure the object get's destroyed */
        img[i] = null;
    }

	public void loadGame(){
		saveGame.open();
		statistic = saveGame.load();
		bet = statistic.getBet();
		saveGame.close();
	}
	
	public void keyEvent(int keycode, int event) {
		// TODO Auto-generated method stub
		if(event == Keyboard.KEY_EVENT_DOWN && currTime==0){
            switch(keycode){
                case Keyboard.KEY_LEFT:
                	GameScreen.currentMenu = (GameScreen.currentMenu - 1 + 2) % 2;
                	positionX();
                    break;
                case Keyboard.KEY_RIGHT:
                	GameScreen.currentMenu = (GameScreen.currentMenu + 1) % 2;
                	positionX();
                    break;
                case Keyboard.KEY_RIGHT_SOFTKEY:
                	un_load_screen();
                	ActionClick(keycode);
                    break;
                default:
                	ActionClick(keycode);
                    break;
            }
        }
	}
	public void ActionClick(int i){
		switch (i) {
		case Keyboard.KEY_RIGHT_SOFTKEY:
			un_load_screen();
			saveGame.open();
			statistic.setBet(bet);
			saveGame.save(statistic);
			saveGame.close();
			canvas.setScreen(new Menu(canvas));
			break;
		case Keyboard.KEY_UP:
			if(statistic.getBankerCapital()>statistic.getGamerCapital()){
				bet = (bet<statistic.getGamerCapital()-100?bet+100:statistic.getGamerCapital());
			}
			else{
				bet = (bet<statistic.getBankerCapital()-100?bet+100:statistic.getBankerCapital());
			}
			try {
				if(canvas.getVolume()>0){
//					if(canvas.sound[Sound.BEEP].getState() == Player.STARTED){
//						canvas.sound[Sound.BEEP].stop();
//					}
					vc = (VolumeControl) canvas.sound[Sound.BEEP].getControl("VolumeControl");
					vc.setLevel(canvas.getVolume());
					canvas.sound[Sound.BEEP].start();
				}
			} catch (MediaException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case Keyboard.KEY_DOWN:
			bet = (bet>=100?bet-100:0);
			try {
				if(canvas.getVolume()>0){
//					if(canvas.sound[Sound.BEEP].getState() == Player.STARTED){
//						canvas.sound[Sound.BEEP].stop();
//					}
					vc = (VolumeControl) canvas.sound[Sound.BEEP].getControl("VolumeControl");
					vc.setLevel(canvas.getVolume());
					canvas.sound[Sound.BEEP].start();
				}
			} catch (MediaException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case Keyboard.KEY_OK:
			if(bet >0){
				update();
				try {
					if(canvas.getVolume()>0){
//						if(canvas.sound[Sound.BEEP].getState() == Player.STARTED){
//							canvas.sound[Sound.BEEP].stop();
//						}
						vc = (VolumeControl) canvas.sound[Sound.DICE].getControl("VolumeControl");
						vc.setLevel(canvas.getVolume());
						canvas.sound[Sound.DICE].start();
					}
				} catch (MediaException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			break;
		default:
			break;
		}
	}
	public void positionX(){
		//bet = 0;		//reset tiền cược nếu đổi cửa
		GameScreen.pos1 = GameScreen.currentMenu*110;
		GameScreen.pos2 = GameScreen.currentMenu*110 + 80;
	}
	
	public void printStatistic(Graphics g){
		g.setColor(255,255,255);
		g.drawString(String.valueOf(statistic.getBankerCapital()), 260, 35, Graphics.LEFT | Graphics.TOP);
		g.drawString(String.valueOf(statistic.getBigCount()), 285, 83, Graphics.RIGHT | Graphics.TOP);
		g.drawString(String.valueOf(statistic.getSmallCount()), 285, 100, Graphics.RIGHT | Graphics.TOP);
		g.drawString(String.valueOf(statistic.getGamerCapital()), 260, 150, Graphics.LEFT | Graphics.TOP);
		g.drawString(String.valueOf(statistic.getWinCount()), 285, 180, Graphics.RIGHT | Graphics.TOP);
		g.drawString(String.valueOf(statistic.getLoseCount()), 285, 200, Graphics.RIGHT | Graphics.TOP);
	}
	
	public void update(){
		bet = statistic.getBankerCapital()<bet?statistic.getBankerCapital():bet;
		bet = statistic.getGamerCapital()<bet?statistic.getGamerCapital():bet;
		
		try {
			diceOne.generator();
			Thread.sleep(100);
			diceTwo.generator();
			Thread.sleep(100);
			diceThree.generator();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		int result = diceOne.getA() + diceTwo.getA() + diceThree.getA();
		if((result <= 10 && GameScreen.currentMenu == GameScreen.SMALL)||(result > 10 && GameScreen.currentMenu == GameScreen.BIG)){
			statistic.setGamerCapital(statistic.getGamerCapital() + bet);
			statistic.setBankerCapital(statistic.getBankerCapital() - bet);
			statistic.setWinCount(statistic.getWinCount() + 1);
		}else{
			statistic.setGamerCapital(statistic.getGamerCapital() - bet);
			statistic.setBankerCapital(statistic.getBankerCapital() + bet);
			statistic.setLoseCount(statistic.getLoseCount() + 1);
		}
		if(result > 10) {
			statistic.setBigCount(statistic.getBigCount() + 1);
		}
		else {
			statistic.setSmallCount(statistic.getSmallCount() + 1);
		}
		startTime = System.currentTimeMillis();
		currTime = 1;
	}
	public int finishGame(){
		if(statistic.getBankerCapital() == 0)
			return WIN;
		else if(statistic.getGamerCapital() == 0)
			return LOSE;
		return CONTINUE;
	}
	public void paint(Graphics g) {
		g.drawImage(img[GameScreen.GAME_BG], 0, 0, Graphics.LEFT | Graphics.TOP);
		g.drawImage(img[GameScreen.SELECTOR], GameScreen.pos1, 220, Graphics.LEFT | Graphics.BOTTOM);
		g.setColor(0,0,0);
		g.drawString(String.valueOf(bet), GameScreen.pos2, 125, Graphics.RIGHT | Graphics.TOP);
		if(currTime>0){
			currTime=System.currentTimeMillis();
			int a = (int)(currTime%6);
			if(currTime-startTime<1000){
				sprite.setFrame(a);
				sprite.setPosition(50, 10);
				sprite.paint(g);
				
				sprite.setFrame(a);
				sprite.setPosition(100, 10);
				sprite.paint(g);
				
				sprite.setFrame(a);
				sprite.setPosition(150, 10);
				sprite.paint(g);
			}
			else if(currTime-startTime<2000){
				
				sprite.setFrame(diceOne.getA()-1);
				sprite.setPosition(50, 10);
				sprite.paint(g);
				
				sprite.setFrame(a);
				sprite.setPosition(100, 10);
				sprite.paint(g);
				
				sprite.setFrame(a);
				sprite.setPosition(150, 10);
				sprite.paint(g);
			}
			else if(currTime-startTime<3000){
				
				sprite.setFrame(diceOne.getA()-1);
				sprite.setPosition(50, 10);
				sprite.paint(g);
				
				sprite.setFrame(diceTwo.getA()-1);
				sprite.setPosition(100, 10);
				sprite.paint(g);
				
				sprite.setFrame(a);
				sprite.setPosition(150, 10);
				sprite.paint(g);
			}
			else currTime = 0;
		}
		else{
			sprite.setFrame(diceOne.getA()-1);
			sprite.setPosition(50, 10);
			sprite.paint(g);
			
			sprite.setFrame(diceTwo.getA()-1);
			sprite.setPosition(100, 10);
			sprite.paint(g);
			
			sprite.setFrame(diceThree.getA()-1);
			sprite.setPosition(150, 10);
			sprite.paint(g);
			printStatistic(g);
			if(finishGame() == WIN || finishGame() == LOSE){
				un_load_screen();
				canvas.setScreen(new FinishGame(canvas, finishGame(), statistic));
			}
		}
		
	}
}
